package com.sinotrans.auth.config.security;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;

import com.sinotrans.common.security.AuthEntity;
import com.sinotrans.common.security.DigestSignature;
import com.sinotrans.common.security.auth.OAuthUtils;

@Component
public class SecurityService {
	static Logger logger = LoggerFactory.getLogger(SecurityService.class);

	@Autowired
	protected DigestSignature digestSignature;

	/**
	 * 权限信息
	 * 
	 * @return
	 */
	public String authinfo() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		AuthEntity authEntity = new AuthEntity();
		// 匿名访问
		if (authentication instanceof OAuth2Authentication) {
			try {
				OAuth2Authentication oauth2Authentication = (OAuth2Authentication) authentication;
				String userid = String.valueOf(oauth2Authentication.getPrincipal());
				List<String> roles = new ArrayList<String>();
				for (GrantedAuthority granted : oauth2Authentication.getAuthorities()) {
					roles.add(granted.getAuthority());
				}
				authEntity.setUid(userid);
				authEntity.setRls(roles);
			} catch (Exception e) {
				logger.error("RequestHeader add Iauthorization error", e);
			}
		}
		authEntity.setIsd(OAuthUtils.False);
		String authinfo = encode(authEntity);
		return authinfo;
	}

	/**
	 * 用户信息编码
	 * 
	 * @param authEntity
	 * @return
	 */
	public String encode(AuthEntity authEntity) {
		String encode = null;
		try {
			encode = digestSignature.encode(authEntity);
		} catch (Exception e) {
			logger.error("digest signature encode authVo error", e);
		}
		return encode;
	}

}
